package com.shenmazong.demo1907amongo.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.demo1907amongo.mapper.ITbBlogMapper;
import com.shenmazong.demo1907amongo.pojo.TbBlog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2021/12/16 10:38
 */

@Component
@EnableScheduling
@Slf4j
public class ElasticSearchTaskWork {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    ITbBlogMapper iTbBlogMapper;

    private Boolean first = true;

    /**
     * @description 每1分钟检查一下ES索引是否创建ES索引
     * @author 军哥
     * @date 2021/12/17 9:04
     * @version 1.0
     */
    @Scheduled(fixedDelay = 1000*60)
    public void createEsIndex() {

        //--1 检查是否执行过了
        if(first) {
            log.info("createEsIndex ...");
            if(!elasticsearchRestTemplate.indexOps(TbBlog.class).exists()) {
                //--1 创建索引
                elasticsearchRestTemplate.indexOps(TbBlog.class).create();

                //--2 创建映射
                Document mapping = elasticsearchRestTemplate.indexOps(TbBlog.class).createMapping();
                elasticsearchRestTemplate.indexOps(TbBlog.class).putMapping(mapping);
            }

            first = false;
        }
    }

    /**
     * @description 定时增量同步数据到ES中，并且延迟1分钟执行
     * @author 军哥
     * @date 2021/12/17 9:13
     * @version 1.0
     */
    @Scheduled(initialDelay = 1000*60, fixedDelay = 1000*60)
    public void syncElasticSearch() {
        // OOM
        List<TbBlog> tbBlogs = iTbBlogMapper.selectList(new QueryWrapper<TbBlog>().lambda().eq(TbBlog::getEsFlag, 0));
        if(tbBlogs == null || tbBlogs.size() <=0 ) {
            return;
        }

        for(TbBlog blog : tbBlogs) {
            //--1 先同步es
            elasticsearchRestTemplate.save(blog);

            //--2 修改数据库状态
            blog.setEsFlag(1);
            iTbBlogMapper.updateById(blog);
        }
    }
}
